package com.cpr.rwqd_sjjn.config;

import com.cpr.rwqd_sjjn.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        // 检查 Token 是否存在
        if (token == null || !token.startsWith("Bearer ")) {
            setUnauthorizedResponse(response, "请先登录");
            return false;
        }

        // 提取 Token
        token = token.substring(7); // 去掉 "Bearer " 前缀

        // 验证 Token
        try {
            String username = jwtUtil.extractClaims(token).getSubject();
            if (!jwtUtil.validateToken(token, username)) {
                setUnauthorizedResponse(response, "Token 无效或已过期，请重新登录");
                return false;
            }
        } catch (Exception e) {
            setUnauthorizedResponse(response, "Token 解析失败，请重新登录");
            return false;
        }

        return true; // Token 验证通过
    }

    /**
     * 设置未授权响应
     */
    private void setUnauthorizedResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value()); // 设置状态码为 401
        response.setContentType("application/json;charset=UTF-8"); // 设置响应类型为 JSON
        response.getWriter().write("{\"message\":\"" + message + "\"}");
    }
}